//
//  NotificationViewController.m
//  FMS
//
//  Created by Steven on 10/15/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "NotificationViewController.h"
#import "DetailedItemViewController.h"
#import "ScheduleInspectionViewController.h"

@interface NotificationViewController ()

@end

@implementation NotificationViewController
@synthesize parent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
        parent = _parent;
    }
    return self;
}

- (void) listSchedule {
    [mainArray removeAllObjects];
    
    currentRecordIndex = 0;
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            
            NSMutableArray *tmpArray = [CouchBaseLiteLib listScheduleByItem:((DetailedItemViewController*)parent).itemDetailedDict from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
//                [mainArray sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"dateUpdated" ascending:NO selector:@selector(compare:)]]];
                
                //check expire for item
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"MMM dd, yyyy"];
                
                NSString *itemId = [((DetailedItemViewController*)parent).itemDetailedDict objectForKey:@"_id"];
                CBLDocument *itemDoc = [CouchBaseLiteLib getDocumentById:itemId];
                NSString *expiredDateStr = [itemDoc propertyForKey:@"date_of_exp"];
                
                if (expiredDateStr != Nil) {
                    NSDate *expiredDate = [dateFormatter dateFromString:expiredDateStr];
                    
                    NSDate* now = [NSDate date];
                    NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                                       components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                                       fromDate:now
                                                       toDate:expiredDate
                                                       options:0];
                    NSInteger year  = [ageComponents year];
                    NSInteger month = [ageComponents month];
                    NSInteger day   = [ageComponents day];
                    
                    if (year == 0 && month <= 1 && day == 0) {
                        //notify expire item
                        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"expiredItem",expiredDateStr,@"expiredDate", nil];
                        [mainArray insertObject:dict atIndex:0];
                    }
                }
                
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreSchedule {
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            
            NSMutableArray *tmpArray = [CouchBaseLiteLib listScheduleByItem:((DetailedItemViewController*)parent).itemDetailedDict from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
//                [mainArray sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"dateUpdated" ascending:NO selector:@selector(compare:)]]];
                
                int previousIndex = currentRecordIndex;
                
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
                isLock = NO;
                
                if (isLoadMore) {
                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _lbNotificationType.text = [dictLanguage objectForKey:@"building-mgmt.notification.type"];
    _lbDescription.text      = [dictLanguage objectForKey:@"building-mgmt.notification.description"];
    _lbStartDate.text        = [dictLanguage objectForKey:@"maintenance-mgmt.inspection.starting-date"];
    
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    mainArray = [NSMutableArray arrayWithCapacity:1];

    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 25, 25)];
    myActivityView.hidesWhenStopped = YES;
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:myActivityView];
    [myActivityView startAnimating];
    
    [self listSchedule];
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
        
        if(!isLoadMore)
        {
            [self.mainTableView hideLoadingMore];
            return;
        }
//        [self.mainTableView showActivity];
        [self listMoreSchedule];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    //    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure the cell...
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    UILabel *lbCellType = [[UILabel alloc] initWithFrame:CGRectMake(72, 20, 200, 21)];
    lbCellType.backgroundColor = [UIColor clearColor];
    lbCellType.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:lbCellType];
    
    UILabel *lbCellStartDate = [[UILabel alloc] initWithFrame:CGRectMake(684, 20, 200, 21)];
    lbCellStartDate.backgroundColor = [UIColor clearColor];
    lbCellStartDate.textColor = [UIColor darkGrayColor];
    lbCellStartDate.text = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]]];
    [cell.contentView addSubview:lbCellStartDate];
    
    UILabel *lbCellDescription = [[UILabel alloc] initWithFrame:CGRectMake(310, 20, 350, 40)];
    lbCellDescription.backgroundColor = [UIColor clearColor];
    lbCellDescription.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:lbCellDescription];
    
    
    BOOL isExpiredItem = [[dict objectForKey:@"expiredItem"] boolValue];
    if (!isExpiredItem) {
        
        int serviceType = [[dict objectForKey:@"itemType"] intValue];
        
        //check Upcoming schedule
        NSTimeInterval todayInterval = [[NSDate date] timeIntervalSince1970];
        
        NSTimeInterval startDateInterval = [[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]] timeIntervalSince1970];
        NSTimeInterval duration = 0.0f;
        duration = 7*24*60*60; //1 week duration
        
        NSDate *now = [NSDate date];
        NSDate *startDate = [NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]];
        NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                           components:NSCalendarUnitDay | NSCalendarUnitMonth | NSYearCalendarUnit
                                           fromDate:now
                                           toDate:startDate
                                           options:0];
        NSInteger dayDuration = [ageComponents day];
        NSInteger monthDuration = [ageComponents month];
        NSInteger yearDuration = [ageComponents year];
        
        //    NSLog(@"day = %d month = %d, year = %d",dayDuration,monthDuration,yearDuration);
        
        //    NSLog(@"today = %@",[NSDate date]);
        //    NSLog(@"startDate = %@",[dict objectForKey:@"startDate"]);
        //
        //    NSLog(@"startDateInterval:%f- today + duration:%f - todayInterval:%f",startDateInterval,todayInterval+duration,todayInterval);
        
        int notificationType;
        NSString *typeName = @"";
        NSString *description = @"";
        
        if (startDateInterval < todayInterval) {
            notificationType = Overdue_Schedule;
            
            typeName = [dictLanguage objectForKey:@"notification.schedule.type.overdue"];
            if (serviceType == Inspection)
                description = [dictLanguage objectForKey:@"notification.schedule.description.inspection-overdue"];
            else
                description = [dictLanguage objectForKey:@"notification.schedule.description.maintenance-overdue"];
        }
        else {
            if (startDateInterval <= todayInterval + duration) {
                //Upcoming
                notificationType = Upcoming_Schedule;
                typeName = [dictLanguage objectForKey:@"notification.schedule.type.upcoming"];
                description = [dictLanguage objectForKey:@"notification.schedule.description.upcoming"];
            }
            else {
                if (serviceType == Inspection) {
                    notificationType = Inspection_Updated;
                    typeName = [dictLanguage objectForKey:@"notification.schedule.type.inspection-updated"];
                    description = [dictLanguage objectForKey:@"notification.schedule.description.inspection-updated"];
                }
                else {
                    notificationType = Maintenance_Updated;
                    typeName = [dictLanguage objectForKey:@"notification.schedule.type.maintenance-updated"];
                    description = [dictLanguage objectForKey:@"notification.schedule.description.maintenance-updated"];
                }
            }
            
            //check expired, before 1 month
            if (dayDuration == 0 && monthDuration == 1 && yearDuration == 0) {
                //display expired label
                UILabel *lbExpired = [[UILabel alloc] initWithFrame:CGRectMake(310, 50, 350, 21)];
                lbExpired.text = [NSString stringWithFormat:@"Expire on: %@",[NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[dict objectForKey:@"startDate"]]]];
                lbExpired.textColor = [UIColor redColor];
                [cell.contentView addSubview:lbExpired];
            }
        }
        
        lbCellDescription.text = description;
        lbCellDescription.numberOfLines = 0;
        [lbCellDescription sizeToFit];
        
        lbCellType.text = typeName;
        
        BOOL isRead = [[dict objectForKey:@"wasRead"] boolValue];
        //set red color for overdue schedule
        if (notificationType == Overdue_Schedule) {
            lbCellDescription.textColor = [UIColor redColor];
            
            if (!isRead) {
                //add image to warning
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconOverdueNotification.png"]];
                imgView.frame = CGRectMake(20, 20, 28, 28);
                [cell.contentView addSubview:imgView];
            }
        }
        else {
            if (!isRead) {
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconNewNotification.png"]];
                imgView.frame = CGRectMake(20, 20, 28, 28);
                [cell.contentView addSubview:imgView];
            }
        }
    }
    else {
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconOverdueNotification.png"]];
        imgView.frame = CGRectMake(20, 20, 28, 28);
        [cell.contentView addSubview:imgView];
        
        lbCellType.text = [dictLanguage objectForKey:@"notification.schedyle.item-expired.title"];
        
        lbCellDescription.text = [dictLanguage objectForKey:@"notification.schedyle.item-expired.message"];
        lbCellDescription.textColor = [UIColor redColor];
        lbCellDescription.numberOfLines = 0;
        [lbCellDescription sizeToFit];
        
        cell.userInteractionEnabled = NO;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dict = [[mainArray objectAtIndex:indexPath.row] mutableCopy];
    BOOL wasRead = [[dict objectForKey:@"wasRead"] boolValue];
    if (!wasRead) {
        [dict setObject:[NSNumber numberWithBool:YES] forKey:@"wasRead"];
        [mainArray replaceObjectAtIndex:indexPath.row withObject:dict];
        
        //get current selected schedule
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dict error:&error];
        if (!error) {
            NSLog(@"update schedule is read");
        }
        
        int currentUnread = ((DetailedItemViewController*)parent).numberUnreadNotification;
        [(DetailedItemViewController*)parent setNotificationAlert:currentUnread-1];
        
        NSArray *indexPathArray = [NSArray arrayWithObjects:indexPath, nil];
        [tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    
    [(DetailedItemViewController*)parent selectDetailedNotification:dict];
}

@end
